package com.mars.rabbitmq.delay;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author King
 * @create 2020/8/19 14:21
 */
@Slf4j
@Component
public class KingOrderProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            log.info("correlationData: " + correlationData);
            log.info("ack: " + ack);
            if (!ack) {
                System.out.println("异常处理....");
            }
        }
    };


    RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
        @Override
        public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
            log.info("return exchange: " + exchange + ", routingKey: "
                    + routingKey + ", replyCode: " + replyCode + ", replyText: " + replyText);
        }
    };

    /**
     * 订单发送到立即消费队列
     *
     * @param msg
     */
    public void convertAndSend(String msg) {
        MessageProperties mp = new MessageProperties();
        Message message = new Message((msg.toString() + "order").getBytes(), mp);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        String orderId = "dd" + System.currentTimeMillis();
        log.info("订单" + orderId + ":支付倒计时....");
        CorrelationData correlationData = new CorrelationData(orderId);
        rabbitTemplate.convertAndSend(DelayOrderRabbitMqConfig.DELAY_EXCHANGE, DelayOrderRabbitMqConfig.DELAY_ROUTING_KEY, message, correlationData);
    }


}
